<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="./style.css" />
  </head>

  <body>
    <div class="textarea-editor-box">
      <textarea id="textarea-editor" style="width:700px;height:300px;">
      </textarea>
      <a href="javascript:;" class="textarea-editor-sendbtn">发送</a>
      <input
        id="uploadImg"
        type="file"
        accept="image/*"
        style="display:none;"
      />
      <input type="file" id="uploadFile" style="display:none;" />
    </div>

    <script src="../plug/qiniu/qiniu.min.js"></script>
    <script src="../plug/qiniu/crypto-js.js"></script>
    <script src="../plug/qiniu/qiniu.upload.token.js"></script>
    <script src="../plug/qiniu/qiniu.upload.formdata.js"></script>
    <script src="../lib/tool.min.js"></script>
    <script src="../lib/interactive.min.js"></script>
    <script src="../lib/all.js"></script>
    <script src="../kindeditor-all.js"></script>
    <script src="../lang/zh-CN.js"></script>
    <script src="./script.js"></script>
    <script>
      var config = {
        items: ["emoticons", "insertfile",""],
        resizeType: 0,
        useContextmenu: false
        // pasteType: 0
      };
      KindEditor.ready(function(K) {
        window.editor = K.create("#textarea-editor", config);

        editor.clickToolbar("image", function() {
          var imgIpt = document.getElementById("uploadImg");
          if (imgIpt) {
            imgIpt.click();
          }
        });

        editor.clickToolbar("insertfile", function() {
          var fileIpt = document.getElementById("uploadFile");
          if (fileIpt) {
            fileIpt.click();
          }
        });

        //读取粘贴板内容
        editor.edit.doc.addEventListener("paste", function(e) {
          if (!(e.clipboardData && e.clipboardData.items)) {
            return;
          }
          console.log(e.clipboardData.items[0]);
          for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
            var item = e.clipboardData.items[i];
            if (item.kind === "string") {
              // console.log(item)
              // // kind=string分两类：text/plain，text/html
              // // text/plain 为纯文本
              // if (item.type === "text/plain") {
              //     item.getAsString(function (str) {
              //         // str 是获取到的字符串
              //         K.appendHtml('#textarea-editor', str);
              //         console.log(str)
              //     })
              // }
              // // text/html html文本
              // if (item.type === "text/html") {
              //     item.getAsString(function (str) {
              //         // str 是获取到的html字符串
              //         K.appendHtml('#textarea-editor', str);
              //         console.log(str)
              //     })
              // }
            } else if (item.kind === "file") {
              var pasteFile = item.getAsFile();
              console.log(pasteFile);
              return;
              // pasteFile就是获取到的文件
              // 上传至七牛云
              uploadFileToQiniu(pasteFile, function(url) {
                var appendHtml =
                  '<a href="' + url + '" rel="lightbox[roadtrip]">';
                appendHtml += '<img src="' + url + '" />';
                appendHtml += "</a>";
                K.appendHtml("#textarea-editor", appendHtml);
              });
            }
          }
        });
      });

      //上传图片
      document.getElementById("uploadImg").onchange = function(event) {
        // var e = event || window.event;
        // e.preventDefault();
        // if (this.value != '') {
        //     // 获取key
        //     document.querySelector('#uploadKey').value = initImageKey('');
        //     // 获取token
        //     document.querySelector('#uploadToken').value = initUploadToken();
        // } else {
        //     // 没选择图片
        //     return false;
        // }
        // qiniuUploadFile();
        // return false;
        var resultFile = this.files[0];

        // base64 upload qiniu
        var reader = new FileReader();
        reader.readAsDataURL(resultFile);
        reader.onload = function(e) {
          var bs64 = e.target.result;
          var pic = bs64;
          var token = initUploadToken();
          var url = "http://upload-z2.qiniup.com/putb64/-1";
          //非华东空间需要根据注意事项 1 修改上传域名
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
              // console.log(xhr.responseText);
              try {
                var res = JSON.parse(xhr.responseText);
                var imgUrl = data_qiniu.domain + res.key;
                console.log(imgUrl);
              } catch (err) {}
            }
          };
          xhr.open("POST", url, true);
          xhr.setRequestHeader("Content-Type", "application/octet-stream");
          xhr.setRequestHeader("Authorization", "UpToken " + token);
          xhr.send(pic.split(",")[1]);
        };

        return;

        if (resultFile) {
          // 上传至七牛云
          uploadFileToQiniu(resultFile, function(url) {
            console.log(url);
          });
        }
      };
      function qiniuUploadFile() {
        var f = new FormData(document.querySelector("#ImguploadForm"));

        ajax.upload(data_qiniu.action, f, function(res) {
          console.log(res);
          if (res.status == 200) {
            var imgURL = data_qiniu.domain + res.data.key;
            console.log(imgURL);
          } else {
            alert("上传失败：" + res.error);
          }
        });
      }

      //上传文件
      document.getElementById("uploadFile").onchange = function(event) {
        var resultFile = this.files[0];
        if (resultFile) {
          // 上传至七牛云
          uploadFileToQiniu(resultFile, function(url) {
            console.log(url);
          });
        }
      };

      // uploadFile
      function uploadFileToQiniu(resultFile, callback) {
        //用当前时间戳命名文件名
        var timeStamp = new Date().getTime();
        var fileName = resultFile.name;
        var idx = fileName.lastIndexOf(".");
        if (idx !== -1) {
          fileName = timeStamp + fileName.substring(idx, fileName.length);
        } else {
          fileName = timeStamp;
        }
        //读文件
        var files = doSave(resultFile, resultFile.type, fileName);
        var key = "test/uploadFile/" + fileName;
        var token = initUploadToken();
        var putExtra = {
          fname: fileName,
          params: {},
          mimeType: [] || null
        };
        var config = {
          useCdnDomain: true,
          region: qiniu.region.z2
        };
        //上传
        var observable = qiniu.upload(files, key, token, putExtra, config);
        var observer = {
          next(res) {
            // console.log(res)
          },
          error(err) {
            // console.log(err)
          },
          complete(res) {
            if (res.key) {
              // 文件路径
              var file_url = data_qiniu.domain + res.key;
              callback(file_url);
            } else {
              //失败，1.6s后重试
              setTimeout(function() {
                uploadFileToQiniu(resultFile);
              }, 1600);
            }
          }
        };
        var subscription = observable.subscribe(observer);
      }
      // 写文件
      function doSave(value, type, name) {
        var blob;
        if (typeof window.Blob == "function") {
          blob = new Blob([value], { type: type });
        } else {
          var BlobBuilder =
            window.BlobBuilder ||
            window.MozBlobBuilder ||
            window.WebKitBlobBuilder ||
            window.MSBlobBuilder;
          var bb = new BlobBuilder();
          bb.append(value);
          blob = bb.getBlob(type);
        }
        return blob;
      }
    </script>
  </body>
</html>
